﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ToppingControl.Models;
using System.IO;
using System.Data;
using WinNemoLib;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace ToppingControl.Controllers
{
    public class TableController : Controller
    {
        //
        // GET: /Table/

        public ActionResult Index()
        {
            return View();
         //   return RedirectToAction("allocate_report", new { prdF = "25/06/2013", prdT= "26/06/2013" });
        }

        public ActionResult ReportViewer()
        {
            return View();
        }

        public ActionResult Get_Table(string table)
        {
           List<ReportModel.Report_DS> list = new List<ReportModel.Report_DS>();
           ReportModel mdSearch = new ReportModel();
           list = mdSearch.GET_ACT_FORTOP();
           if (list.Count() <= 0)
           {
              list= new List<ReportModel.Report_DS>();
           }

           return View(list);
        }

        public void Export(string table, string prdF, string prdT)
        {
           //if (table == "HEAD")
           //{
           //   Table_Head_Tail();
           //}
           //else if (table == "waste")
           //{
           //   WASTE();
           //} else if (table == "compound")
           //{
           //   COMPOUND();
           //}
           //else if (table == "bom")
           //{
           //   BOMTOPCORD();
           //}
           //else if (table == "compound_ch")
           //{
           //    COMPOUND_CH();
           //}
        }

        public void BOMTOPCORD()
        {
           string col = "\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\"";
           StringWriter sw = new StringWriter();
           sw.WriteLine(string.Format(col, "topcrdcd", "tcrdcd", "irccrdcd", "compcd", "stdform", "age"));
           List<TopCordBomModel.TopCordBom_DS> list = new List<TopCordBomModel.TopCordBom_DS>();
           TopCordBomModel mdSearch = new TopCordBomModel();
           list = mdSearch.SEL_TOPCORDBOM();

           foreach (TopCordBomModel.TopCordBom_DS item in list)
           {
              sw.WriteLine(string.Format(col, item._Topcrdcd, item._Tcrdcd, item._Irccrdcd, item._Compcd, item._Stdform, item._Age));
           }
           Response.AddHeader("Content-Disposition", "attachment; filename=BomTopcord.csv");
           Response.ContentType = "text/csv";
           Response.ContentEncoding = System.Text.Encoding.GetEncoding("TIS-620");
           Response.Write(sw);
           Response.End();
        }

        public void WASTE(string prdF, string prdT)
        {
            string col = "\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\"";
           StringWriter sw = new StringWriter();

           if (StrUtil.IsNotEmpty(prdF) && StrUtil.IsNotEmpty(prdT))
           {
               sw.WriteLine(string.Format("\"{0}\",\"{1}\"", "Date : ", prdF + "-" + prdT));
           }
           else if (StrUtil.IsNotEmpty(prdF))
           {
               sw.WriteLine(string.Format("\"{0}\",\"{1}\"", "Date : ", prdF));
           }
           sw.WriteLine();
           sw.WriteLine(string.Format(col,"topno","wsdate","shift","matcd","Lot","reason","qty","empdate","empname"));
           List<Top_Waste.TOP_WASTE_DS> list = new List<Top_Waste.TOP_WASTE_DS>();
           Top_Waste mdSearch = new Top_Waste();
           list=mdSearch.LIST_WAS(prdF,prdT);
           foreach (Top_Waste.TOP_WASTE_DS item in list)
           {
                sw.WriteLine(string.Format(col,item._Topno,item._Wsdate,item._Shift,item._Matcd,item._Lot,item._Reason,item._Qty,item._Empdate,item._Empname));
           }
           Response.AddHeader("Content-Disposition", "attachment; filename=WASTE.csv");
           Response.ContentType = "text/csv";
           Response.ContentEncoding = System.Text.Encoding.GetEncoding("TIS-620");
           Response.Write(sw);
           Response.End();
        }
        public void COMPOUND(string prdF, string prdT)
        {
            string col = "\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\"";
           StringWriter sw = new StringWriter();

           if (StrUtil.IsNotEmpty(prdF) && StrUtil.IsNotEmpty(prdT))
           {
               sw.WriteLine(string.Format("\"{0}\",\"{1}\"", "Date : ", prdF + "-" + prdT));
           }
           else if (StrUtil.IsNotEmpty(prdF))
           {
               sw.WriteLine(string.Format("\"{0}\",\"{1}\"", "Date : ", prdF));
           }
           sw.WriteLine();
           sw.WriteLine(string.Format(col, "topno", "compdate","shift", "compcd","complot", "compused", "empdate", "empname"));
           List<CompoundUseModel.CompoundUse_DS> list = new List<CompoundUseModel.CompoundUse_DS>();
           CompoundUseModel mdSearch = new CompoundUseModel();
           list = mdSearch.LIST_COMPUSED(prdF,prdT);
           foreach (CompoundUseModel.CompoundUse_DS item in list)
           {
              sw.WriteLine(string.Format(col, item._Topno, item._Compdate,item._Shift, item._Compcd,item._Complot, item._Compused, item._Empdt, item._Empname));
           }
           Response.AddHeader("Content-Disposition", "attachment; filename=compused.csv");
           Response.ContentType = "text/csv";
           Response.ContentEncoding = System.Text.Encoding.GetEncoding("TIS-620");
           Response.Write(sw);
           Response.End();
        }

        public void COMPOUND_CH(string prdF, string prdT)
        {
            string col = "\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\"";
            StringWriter sw = new StringWriter();
            if (StrUtil.IsNotEmpty(prdF) && StrUtil.IsNotEmpty(prdT))
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\"", "Date : ", prdF + "-" + prdT));
            }
            else if (StrUtil.IsNotEmpty(prdF))
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\"", "Date : ", prdF));
            }
            sw.WriteLine();
            sw.WriteLine(string.Format(col, "topno", "plandt", "itemno", "rollfm", "compcd", "complot", "comppllt", "compexp", "compw", "cauthemp", "creatxt", "cshtxt"));

            List<ReportModel.Report_DS> list = new List<ReportModel.Report_DS>();
            ReportModel mdSearch = new ReportModel();
            list = mdSearch.GET_COMPOUND_CH(prdF,prdT);
            foreach (ReportModel.Report_DS item in list)
            {
                sw.WriteLine(string.Format(col, item._pTopno,
                    item._pPlandt,
                    item._pItemno,
                    item._aRollno,
                    item._pCompcd, 
                    item._pComplot, 
                    item._pComppllt,
                    item._pCompexp,
                    item._pCompw, 
                    item._pEmpname, 
                    item._pCreatxt,
                    item._pCshtxt));
            }
            Response.AddHeader("Content-Disposition", "attachment; filename=compound_change.csv");
            Response.ContentType = "text/csv";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("TIS-620");
            Response.Write(sw);
            Response.End();
        }

        public void Table_Head_TailS(string prdF, string prdT)
        {

           List<ReportModel.Report_DS> list = new List<ReportModel.Report_DS>();
           ReportModel mdSearch = new ReportModel();
           list = mdSearch.GET_ACT_FORTOP("",prdF,prdT);
           if (list.Count() <= 0)
           {
              list = new List<ReportModel.Report_DS>();
           }

           StringWriter sw = new StringWriter();
           if (StrUtil.IsNotEmpty(prdF) && StrUtil.IsNotEmpty(prdT))
           {
               sw.WriteLine(string.Format("\"{0}\",\"{1}\"", "Date : ", prdF + "-" + prdT));
           }
           else if (StrUtil.IsNotEmpty(prdF))
           {
               sw.WriteLine(string.Format("\"{0}\",\"{1}\"", "Date : ", prdF));
           }
           sw.WriteLine();

           //First line for column names
           string col = "\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\",\"{14}\",\"{15}\",\"{16}\",\"{17}\",\"{18}\",\"{19}\",\"{20}\",\"{21}\",\"{22}\",\"{23}\",";
           col = col + "\"{24}\",\"{25}\",\"{26}\",\"{27}\",\"{28}\",\"{29}\",\"{30}\",\"{31}\",\"{32}\",\"{33}\",\"{34}\",\"{35}\",\"{36}\",\"{37}\",\"{38}\",\"{39}\",\"{40}\",\"{41}\",\"{42}\",\"{43}\",\"{44}\",\"{45}\",\"{46}\",\"{47}\",";
           col = col + "\"{48}\",\"{49}\",\"{50}\",\"{51}\",\"{52}\",\"{53}\",\"{54}\",\"{55}\",\"{56}\",\"{57}\",\"{58}\",\"{59}\",\"{60}\",\"{61}\",\"{62}\",\"{63}\",\"{64}\",\"{65}\",\"{66}\",\"{67}\"";
           sw.WriteLine(string.Format(col, "topno",
                              "plandt",
                              "itemno",
                              "topcrdcd",
                              "manufc",
                              "length",
                              "Plansts",
                              "Uptemp",
                              "Uptdat",
                              "Skpflag","Skpdt","Skpemp","skpshtxt",
                              "Smpshemp","Smpshtxt",
                              "actflag",
                              "actdt",
                              "runflag",
                              "Rundat",
                              "empname",
                              "shift",
                              "finflag",
                              "findat",
                              "Tcrdcd",
                              "Tcrdlot",
                              "tcrdexp",
                              "Tcrdtagl",
                              "Tcrdtagw",
                              "tcrdw",
                              "tauthemp",
                              "treatxt",
                              "Compcd",
                              "tshtxt",
                              "Complot",
                              "Comppllt",
                              "Compexp",
                              "compw",
                              "Cauthemp",
                              "creatxt",
                              "cshtxt",
                              "sample",
                              "prddate",
                              "rollno",
                              "length",
                              "width",
                              "expired",
                              "ds50",
                              "os50",
                              "wd50",
                              "ds100",
                              "os100",
                              "wd100",
                              "ds200",
                              "os200",
                              "wd200",
                              "ds300",
                              "os300",
                              "wd300",
                              "ds400",
                              "ms400",
                              "os400",
                              "wd400",
                              "stdused",
                              "empname",
                              "shift",
                              "updat",
                              "finflag",
                              "findat"

                              ));
           foreach (ReportModel.Report_DS item in list)
           {
              sw.WriteLine(string.Format(col, item._pTopno,
                               item._pPlandt,
                               item._pItemno,
                               item._pTopcrdcd,
                               item._pManufc,
                               item._pLength,
                               item._pPlants,
                               item._pUpTemp,
                               item._pUptdat,
                               item._Skpflag,item._skpdt, item._skpemp,item._skpshtxt,
                               item._smpemp, item._smpshtxt,
                               item._pActflag,
                               item._pActdt,
                               item._pRunflag,
                               item._pRundt,
                               item._pEmpname,
                               item._pShift,
                               item._pFinflag,
                               item._pFindt,
                               item._pTcrdcd,
                               item._pTcrdlot,
                               item._pTcrdexp,
                               item._pTcrdtagl,
                               item._pTcrdtagw,
                               item._pTcrdw,
                               item._pTauthemp,
                               item._pTreatxt,
                               item._pCompcd,
                               item._pTshtxt,
                               item._pComplot,
                               item._pComppllt,
                               item._pCompexp,
                               item._pCompw,
                               item._pCauthemp,
                               item._pCreatxt,
                               item._pCshtxt,
                               item._pSample,
                               item._aPrddate,
                               item._aRollno,
                               item._aLenght,
                               item._aWidgth,
                               item._aExpired,
                               item._a50ds,
                               item._a50os,
                               item._a50wd,
                               item._a100ds,
                               item._a100os,
                               item._a100wd,
                               item._a200ds,
                               item._a200os,
                               item._a200wd,
                               item._a300ds,
                               item._a300os,
                               item._a300wd,
                               item._a400ds,
                               item._a400ms,
                               item._a400os,
                               item._a400wd,
                               item._aStdUsed,
                               item._aEmpname,
                               item._aShift,
                               item._aUpdate,
                               item._aFinflag,
                               item._aFindat));
           }

           Response.AddHeader("Content-Disposition", "attachment; filename=REPORT.csv");
           Response.ContentType = "text/csv";
           Response.ContentEncoding = System.Text.Encoding.GetEncoding("TIS-620");
           Response.Write(sw);
           Response.End();
        }


        public ActionResult Table_Head_Tail(string prdF, string prdT)
        {
            try
            {
                Models.ReportModel s = new Models.ReportModel();
                ReportClass report = new ReportClass();
                ReportDocument rp = new ReportDocument();

                rp.FileName = Server.MapPath(@"~\Report\Head_Tail.rpt");
                rp.Load(rp.FileName);
                rp.PrintOptions.PaperSize = PaperSize.PaperA3;
                rp.PrintOptions.PaperOrientation = CrystalDecisions.Shared.PaperOrientation.Landscape;
                
                ReportModel mdSearch = new ReportModel();

                DataTable dt1 = mdSearch.GET_ACT_FORTOP_DT("", prdF, prdT);

                if (dt1 == null)
                {
                    dt1 = new DataTable();
                }

                dt1.TableName = "RptHeadNTail";
                DataSet ds = new DataSet();
                ds.Tables.Add(dt1.Copy());
                rp.SetDataSource(ds);

                Stream stream = rp.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                return File(stream, "application/pdf");
            
            }
            catch (Exception ex)
            {
                return Content(ex.ToString() + "ไม่พบข้อมูล");
                throw;
            }
          
        }


        public void allocate_report(string prdF ,string prdT)
        {
            int rowST = 0;
            int rowEnd = 0;
            ReportModel mdSearch = new ReportModel();
            DataTable dt = mdSearch.GET_REPORT(prdF,prdT);
            List<ReportModel.Report_DS> list = new List<ReportModel.Report_DS>();

            if (dt !=null)
            {
                DataRow items = dt.Rows[0];

                int rowno = Convert.ToInt16(items["rollno"]);
                string itemno = items["itemno"].ToString();
                for (int i = 1; i <= dt.Rows.Count-1; i++)
                {
                    items = dt.Rows[i];

                    if (itemno != items["itemno"].ToString())
                    {
                        rowEnd = i - 1;
                        list = Allcate_Report(rowST, rowEnd, list, dt);
                        rowST = i;

                    }
                    else if (rowno > Convert.ToInt16(items["rollno"]))
                    {
                        rowEnd = i - 1;
                        list = Allcate_Report(rowST, rowEnd, list, dt);
                        rowST = i;
                        rowno = Convert.ToInt16(items["rollno"]);
                        itemno = items["itemno"].ToString();
                    }
                    rowno = Convert.ToInt16(items["rollno"]);
                    itemno = items["itemno"].ToString();
                }


                list = Allcate_Report(rowST, dt.Rows.Count-1 , list, dt);
            }

            string col = "\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\",\"{14}\",\"{15}\",\"{16}\",\"{17}\",\"{18}\"";
            StringWriter sw = new StringWriter();

            if (StrUtil.IsNotEmpty(prdF) && StrUtil.IsNotEmpty(prdT))
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\"", "Date : ", prdF + "-" + prdT));
            }
            else if (StrUtil.IsNotEmpty(prdF))
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\"", "Date : ", prdF));
            }
            sw.WriteLine();


            sw.WriteLine(string.Format(col, "topno", "plandt", "itemno", "topcrdcd", "manufc", "length", "Tcrdcd", "Tcrdlot", "Compcd", "Complot", "comppllt", "compexp", "compw", "prddate", "rollno", "length", "stdused","allcate",""));

            foreach (ReportModel.Report_DS item in list)
            {
                sw.WriteLine(string.Format(col,item._pTopno, item._pPlandt, item._pItemno,item._pTopcrdcd,item._pManufc,item._pLength,item._pTcrdcd,item._pTcrdlot,
                item._pCompcd, item._pComplot, item._pComppllt, item._pCompexp,item._pCompw,item._aPrddate, item._aRollno,item._aLenght, item._aStdUsed, item._allcate,""));
            }
            Response.AddHeader("Content-Disposition", "attachment; filename=REportAllcate.csv");
            Response.ContentType = "text/csv";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("TIS-620");
            Response.Write(sw);
            Response.End();
        }

        public List<ReportModel.Report_DS> Allcate_Report(int s,int e, List<ReportModel.Report_DS> list,DataTable dt)
        {

            

            ReportModel mdSearch = new ReportModel();
          
            DataRow items = dt.Rows[s];
            if (s == e)
            {
                ReportModel.Report_DS model = new ReportModel.Report_DS();
                model = GET_ROWDATA(items);
                list.Add(model);
                return list;
            }

            string comlot = GET_ROWDATA(items)._pComplot;
            string Comppllt = GET_ROWDATA(items)._pComppllt;
            int rowno = Convert.ToInt16(items["rollno"]);
            double useCom = Convert.ToDouble(items["stdused"]);
            DataTable dtCom = null;
            double x1 = 0;
            string  oldComp = "";
            for (int i = s; i <= e; i++)
            {      
               // int rowno= Convert.ToInt16(items["rollno"]);
                ReportModel.Report_DS model = new ReportModel.Report_DS();
                items = dt.Rows[i];
                model = GET_ROWDATA(items);

                if (StrUtil.IsEmpty(model._pTopcrdcd))
                {
                    comlot = model._pComplot;
                    Comppllt = model._pComppllt;
                    model._pCompcd = items["compcd"].ToString();
                    model._pComplot = items["Complot"].ToString();
                    model._pComppllt = items["Comppllt"].ToString();
                    model._pCompexp = DateUtil.ToDisplayDate(items["Compexp"], DateUtil.eLanguage.EN);

                    items = dt.Rows[i - 1];

                    model._pTopcrdcd = items["topcrdcd"].ToString();
                    model._pTcrdcd = items["Tcrdcd"].ToString();
                    model._pLength = items["length"].ToString();
                    model._pTcrdlot = items["Tcrdlot"].ToString();
                    model._pManufc = items["manufc"].ToString();
                    model._aPrddate = DateUtil.ToDisplayDate(items["prddate"], DateUtil.eLanguage.EN);
                    model._pCompw = items["compw"].ToString();
                    model._aStdUsed = items["stdused"].ToString();
                    model._aLenght = items["alength"].ToString();
                    
                    items = dt.Rows[i];
                
                   
                }
                model._pComplot = comlot;
                model._pComppllt = Comppllt;
                model._allcate = "";
                useCom = Convert.ToDouble(model._aStdUsed);

                

                if (x1 < 0)
                {//มีค่าติดลบ
                    if (oldComp == comlot)
                    {
                        x1 = 0;
                    }else
                    {
                    dtCom = mdSearch.GET_COMP_USE(model._aPrddate, model._pCompcd, comlot);
                    if (dtCom == null) x1 = 0;
                        else
                        {
                            oldComp = comlot;
                            model._pSample = dtCom.Rows[0]["compused"].ToString() ;
                            x1 = Math.Abs(x1);
                            if ((Convert.ToDouble(model._pSample) < Math.Abs(x1)))
                            {
                                x1 = Convert.ToDouble(dtCom.Rows[0]["compused"]) - Math.Abs(x1);
                            }
                            else
                            {
                                useCom = Math.Abs(x1);
                                x1=Convert.ToDouble(model._pSample) - x1;
                            }
                            dtCom.Rows.RemoveAt(0);
                            if (dtCom.Rows.Count <= 0) dtCom = null;
                        }
                    }
                }else if (x1==0 && StrUtil.IsNotEmpty(oldComp)){
                    if (oldComp != comlot)
                    {
                        dtCom = mdSearch.GET_COMP_USE(model._aPrddate, model._pCompcd, comlot);
                        if (dtCom != null)
                        {
                            oldComp = comlot;
                            x1 = Convert.ToDouble(dtCom.Rows[0]["compused"]);
                            model._pSample = x1.ToString();
                            dtCom.Rows.RemoveAt(0);
                            if (dtCom.Rows.Count <= 0) dtCom = null;
                        }
                    }
                }

                rowno = Convert.ToInt16(model._aRollno);
                if (rowno == 1)
                {
                 dtCom=  mdSearch.GET_COMP_USE(model._aPrddate, model._pCompcd, comlot);
               
                    if (dtCom != null)
                    {
                        oldComp = comlot;
                        x1 = Convert.ToDouble(dtCom.Rows[0]["compused"]);
                        model._pSample = x1.ToString();
                        dtCom.Rows.RemoveAt(0);
                        if (dtCom.Rows.Count <= 0) dtCom = null;
                    }
                }

                if (x1 >= useCom)
                {
                    x1 = x1 - useCom;
                    model._allcate = useCom.ToString();
                    if (x1 == 0)
                    {
                        x1 = 0;
                    }
                }
                else if(x1 < useCom && x1 !=0)
                {
                    if (x1 < 0)
                    {
                        double com = Convert.ToDouble(model._pSample) - Convert.ToDouble(list[i - 1]._allcate);
                        model._allcate = com.ToString();
                        x1 = 0;
                    }
                    else
                    {
                        model._allcate = x1.ToString();
                        x1 = x1 - useCom;
                    }
                  //  x1 = x1 * -1;
                }

         


                list.Add(model);
            }
                
               
               
            return list;
            ////////////  WR
        
        }
   
       
        public ReportModel.Report_DS GET_ROWDATA(DataRow items)
        {
            ReportModel.Report_DS model = new ReportModel.Report_DS();
            model._pPlandt = DateUtil.ToDisplayDate(items["plandt"], DateUtil.eLanguage.EN);
            model._pCompcd = items["compcd"].ToString();
            model._pComplot = items["Complot"].ToString();
            model._pComppllt = items["Comppllt"].ToString();
            model._pCompexp = DateUtil.ToDisplayDate(items["Compexp"], DateUtil.eLanguage.EN);
            model._pCompw = items["compw"].ToString();
            model._pTopno = items["topno"].ToString();
            model._pItemno = items["itemno"].ToString();
            model._pTopcrdcd = items["topcrdcd"].ToString();
            model._pTcrdcd = items["Tcrdcd"].ToString();
            model._pLength = items["length"].ToString();
            model._pTcrdlot = items["Tcrdlot"].ToString();
            model._pManufc = items["manufc"].ToString();
            model._aPrddate = DateUtil.ToDisplayDate(items["prddate"], DateUtil.eLanguage.EN);
            model._aRollno = items["rollno"].ToString();
            model._aLenght = items["alength"].ToString();
            model._aStdUsed = items["stdused"].ToString();
            return model;
        }
      }


    }

